<?php

/* 
 * Project: colobok
 * and open the template in the editor.
 * @author: Sviatoslav Mysachenko <svyatoslavik@gmail.com>
 */

class MongoDBCollection implements \Countable, \ArrayAccess, \Iterator{
    private $__mongoCursor = null;
    private $__className = null;
    private $__array = array();
    public function __construct($mongoCursor, $itemsClassName) {
        $this->__mongoCursor = $mongoCursor;
        $this->__className = $itemsClassName;
    }
    
    public function getItemsClassName(){
        return $this->__className;
    }
    
    public function offsetExists($offset) {
        $arr =  $this->toArray();
        return isset ($arr[$offset]);
    }

    public function offsetGet($offset) {
        $arr =  $this->toArray();
        return $arr[$offset];
    }

    public function offsetSet($offset, $value) {
        $arr =  $this->toArray();
        $arr[$offset] = $value;
    }

    public function offsetUnset($offset) {
        $arr =  $this->toArray();
        unset ($arr[$offset]);
    }

    public function count() {
        return $this->__mongoCursor->count();
    }

    public function current() {
        
        return new $this->__className($this->__mongoCursor->current());        
    }

    public function key() {
        return $this->__mongoCursor->key();
    }

    public function next() {
        $this->__mongoCursor->next();
    }

    public function rewind() {
        $this->__mongoCursor->rewind();
    }

    public function valid() {
        return $this->__mongoCursor->valid();
    }
    public function toArray(){
        if(!$this->__array)
            foreach($this->__mongoCursor as $data)
                $this->__array[] = new $this->__className($data);
        return $this->__array;
    }
    public function getCursor(){
        return $this->__mongoCursor;
    }
    public function limit($limit){
        $this->__mongoCursor->limit($limit);
    }
    public function sort($sort){
        $this->__mongoCursor->sort($sort);
    }
    public function offset($offset){
        $this->__mongoCursor->skip($offset);
    }
}
